/* eslint-disable */
import Vue from 'vue'
import VueGridLayout from 'vue-grid-layout'

import tablegadget from '@/components/gadget/table-two-dimensions-gadget/table-two-dimensions-gadget'
import radarchartgadget from '@/components/gadget/chart-radar/radar-gadget'
import chartgridgadget from '@/components/gadget/chart-grid-gadget/chart-grid-gadget'
import pvtable from '@/components/gadget/pvtable/pvtable-gadget.vue'
import scattergadget from '@/components/gadget/scatter/scatter-gadget.vue'
import grid from '@/components/gadget/grid/grid-gadget.vue'
import checklistgadget from '@/components/gadget/check-list/checklist-gadget.vue'
import gridgadget from '@/components/gadget/grid-gadget/grid-gadget.vue'
import hierarchygridgadget from '@/components/gadget/hierarchy-grid/hierarchygrid-gadget.vue'
import crudformgadget from '@/components/gadget/crud-form/crudform-gadget.vue'
import chartgadget from '@/components/gadget/chart-line/line-gadget.vue'
import barchartgadget from '@/components/gadget/chart-bar/bar-gadget.vue'
import bar3dchartgadget from '@/components/gadget/bar3d-gadget/bar3d-gadget.vue'
import piechartgadget from '@/components/gadget/chart-pie/pie-gadget.vue'
import listmenu from '@/components/gadget/list-menu/list-menu-gadget.vue'
import dateRangeSlicer from '@/components/gadget/dateRange-slicer/daterange-gadget.vue'
import dateSlicer from '@/components/gadget/date-slicer/date-slicer-gadget.vue'
import runReport from '@/components/gadget/runreport-action/runreport-gadget.vue'
import kpigadget from '@/components/gadget/kpi/kpi-gadget.vue'
import circulargauge from '@/components/gadget/circular-gauge/circular-gadget.vue'
import cardicon from '@/components/gadget/card-icon/card-icon-gadget.vue'
import cardlinegadget from '@/components/gadget/card-line/card-line-gadget.vue'
import autorefreshgadget from '@/components/gadget/auto-refresh/auto-refresh-gadget.vue'
import dropdownlistgadget from '@/components/gadget/dropdown-list-slicer/dropdown-list-gadget.vue'
import cascadergadget from '@/components/gadget/cascader-slicer/cascader-gadget.vue'
import treegridgadget from '@/components/gadget/tree-grid-gadget/tree-grid-gadget.vue'
import menulistgadget from '@/components/gadget/customized/menuList/menuList-gadget.vue'
import linkbuttongadget from '@/components/gadget/link-button/link-button-gadget.vue'
import checkboxgadget from '@/components/gadget/checkbox-slicer/checkbox-gadget.vue'
import multiselectgadget from '@/components/gadget/multi-select-slicer/multi-select-gadget'
import cardnumbergadget from '@/components/gadget/card-number/card-number-gadget.vue'
import litikugadget from '@/components/gadget/litiku/litikugadget.vue'
import processgaugegadget from '@/components/gadget/gauge-stage/gauge-stage-gadget.vue'
import htmleditorgadget from '@/components/gadget/html-editor/html-editor-gadget.vue'
// import treemapgadget from '@/components/gadget/tree-map/tree-map-gadget.vue'
import drilldowntreemapgadget from '@/components/gadget/drilldown-treemap/drilldown-treemap-gadget.vue'
import placeholdergadget from '@/components/gadget/place-holder/place-holder-gadget.vue'
import formviewdatagadget from '@/components/gadget/form-view-data/form-view-data-gadget.vue'
// import processgaugegadget from '@/components/gadget/process-gauge/process-gauge-gadget.vue'
import cardlablegadget from '@/components/gadget/card-lable/card-lable-gadget.vue'
import kanbangadget from '@/components/gadget/kanban/kanban-gadget'
import pageheadergadget from '@/components/gadget/page-header/page-header-gadget.vue'
import deptdefaultslicergadget from '@/components/gadget/customized/dept-default-slicer/dept-default-slicer-gadget.vue'
import nextticketviewgadget from '@/components/gadget/next-ticket-view/next-ticket-view-gadget'
import {
  getUUID
} from '@/utils'
import pvtablegadget from '@/components/gadget/pvtable-gadget/pvtable-gadget.vue'
import scorecardgadget from '@/components/gadget/score-card-gadget/score-card-gadget.vue'
// Customized
import bottriggerreportgadget from '@/components/gadget/customized/bot-trigger/bot-trigger-gadget.vue'
import bottriggerpvtablegadget from '@/components/gadget/customized/bot-trigger/bot-trigger-pvtble-gadget.vue'
import bottriggeruserreportgadget from '@/components/gadget/customized/bot-trigger-user/bot-trigger-user-gadget.vue'
import crudgadget from '@/components/gadget/crud-gadget/crud-gadget.vue'
import stepgadget from '@/components/gadget/step-line/step-line-gadget.vue'
import newstepgadget from '@/components/gadget/new-step-line/new-step-line-gadget.vue'
import homepagegadget from '@/components/gadget/home-page/home-page-gadget.vue'
import customizedmultiselectgadget from '@/components/gadget/customized/multi-select-slicer/multi-select-gadget'
import customizeduserdropdownlistgadget from '@/components/gadget/customized/user-dropdown-list-slicer/user-dropdown-list-gadget.vue'
import customizedusermultipledropdownlistgadget from '@/components/gadget/customized/user-multiple-dropdown-list-slicer/user-multiple-dropdown-list-gadget.vue'
import charthourglassgadget from '@/components/gadget/chart-funnel/funnel-gadget.vue'
import usertimezoneinfocardgadget from '@/components/gadget/customized/user-timezone-info-card/user-timezone-info-card-gadget.vue'
import attendancegadget from '@/components/gadget/customized/attendance-gadget/attendance-gadget.vue'
import recordgadget from '@/components/gadget/customized/record-gadget/record-gadget.vue'
import usergadget from '@/components/gadget/customized/user-gadget/user-gadget.vue'
import botsgadget from '@/components/gadget/customized/bots-gadget/bots-gadget.vue'
import workschedulegadget from '@/components/gadget/customized/workschedule-gadget/workschedule-gadget.vue'
import heatmapgadget from '@/components/gadget/chart-heatmap/heatmap-gadget'
import ganttgadget from '@/components/gadget/gantt/gantt-gadget'
import sunburstgadget from '@/components/gadget/chart-sunburst/sunburst-gadget'
// dashboardGadgetList
import {
  dashboardGadgetList,
  slicerGadgetTypeList
} from '@/utils/data-json'
// test gadget
import edwinTestGadget from '@/components/gadget/edwin-test-gadget/edwin-test-gadget'
import enterinputgadget from '@/components/gadget/enter-input-slicer/enter-input-gadget.vue'
import Cookies from 'js-cookie'
import {
  InterceptContext
} from '@/components/storybook/s-Intercept/intercept-context'

import {
  setStyle
} from 'element-ui/lib/utils/dom'
import crudformplusgadget from '@/components/gadget/crud-form-plus/crudform-plus-gadget.vue'
import BDashboardAddWidget from '@/components/storybook/b-dashboard-add-widget/index';
import {useCssVars} from '@/components/storybook/hooks/useCssVar'
import { union, omit, debounce } from "lodash"
import CryptoJS from 'crypto-js'
import { parseQueryString } from '@/utils/common'
import apigridgadget from '@/components/gadget/api-grid-gadget/api-grid-gadget.vue'
import { queryToObject } from '@/components/storybook/utilties/tools'

export default {
  components: {
    tablegadget,
    radarchartgadget,
    chartgridgadget,
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    grid,
    scattergadget,
    checklistgadget,
    gridgadget,
    hierarchygridgadget,
    crudformgadget,
    htmleditorgadget,
    pvtable,
    chartgadget,
    barchartgadget,
    bar3dchartgadget,
    piechartgadget,
    heatmapgadget,
    listmenu,
    dateRangeSlicer,
    runReport,
    kpigadget,
    circulargauge,
    cardicon,
    cardlinegadget,
    dateSlicer,
    autorefreshgadget,
    dropdownlistgadget,
    enterinputgadget,
    cascadergadget,
    treegridgadget,
    menulistgadget,
    linkbuttongadget,
    checkboxgadget,
    multiselectgadget,
    cardnumbergadget,
    litikugadget,
    formviewdatagadget,
    // gaugestagegadget,
    // treemapgadget,
    drilldowntreemapgadget,
    scorecardgadget,
    placeholdergadget,
    processgaugegadget,
    cardlablegadget,
    kanbangadget,
    pageheadergadget,
    pvtablegadget,
    // Customized
    bottriggerreportgadget,
    bottriggerpvtablegadget,
    bottriggeruserreportgadget,
    crudgadget,
    stepgadget,
    newstepgadget,
    homepagegadget,
    customizedmultiselectgadget,
    customizeduserdropdownlistgadget,
    customizedusermultipledropdownlistgadget,
    deptdefaultslicergadget,
    nextticketviewgadget,
    usertimezoneinfocardgadget,
    // Test gadget
    edwinTestGadget,
    charthourglassgadget,
    attendancegadget,
    recordgadget,
    usergadget,
    botsgadget,
    workschedulegadget,
    crudformplusgadget,
    ganttgadget,
    BDashboardAddWidget,
    apigridgadget,
    RemoteGadget:()=>import("@/components/gadget/remote-gadget/remote-gadget.vue"),
    sunburstgadget,
    AIChartGadget:()=>import("@/components/gadget/ai-chart/ai-chart-gadget.vue"),
  },
  provide () {
    return {
      gadgetMessageBus: this.gadgetMessageBus,
      getSlicer: () => this.slicer,
      getFilters: () => this.filters,
      gadgetInfos: () => this.gadgetInfos,
      getSlicerComponents: () => this.slicerComponents,
      getGadgetLoadingStatus: () => this.gadgetLoadingStatus,
      clonable: () => this.clonable,
      dashboardsDetailsData: () => this.dashboardsDetailsData,
      pageFrom:this.pageFrom,
      excludeGadgetType:this.excludeGadgetType,
      getThemeSetting: ()=>this.themeSetting,
      getTheme: ()=>this.curTheme
    }
  },
  data () {
    return {
      pageId: this.$getQuery('pageid'),
      gadgetMessageBus: new Vue(),
      slicer: {},
      filters: [],
      gadgetInfos: [],
      showCloseIcon: true,
      contenttemplateVue: '',
      editMode: false,
      editText: 'Edit',
      dashbordDefaultSetting: {
        allowResizing: false,
        allowDragging: false,
        responsive: true
      },
      gadgets: [],
      dialog: false,
      selectedgadget: '',
      loading: false,
      widgetLoading: false,
      layoutLists: dashboardGadgetList,
      userGadgetList: [],
      showMsg: false,
      businessTypeForWidget: '',
      reportNameForPage: '',
      reportIntegrationCode: [],
      layoutType: '',
      layoutSetting: null,
      layoutId: null,
      dashboardSetting: {
        size: "A4", 
        orientation: "portrait"
      },
      dialogOptions: false,
      gadgetLoadingStatus: [],
      dashboardId: null,
      isInDesktop: false,
      permission: false,
      authLoading: false,
      gadgetChoiceModalVisible: false,
      clonable: undefined,
      dashboardsDetailsData: {},
      isFullScreen: false,
      fullScreenData: {},
      curTheme:"white",
      themeSetting:{},
      otherPageSlicers: [],
    }
  },

  computed: {
    publishedLayoutItems () {
      return this.layoutLists.filter(item => item.group === 'published')
    },
    inDevLayoutItems () {
      return this.layoutLists.filter(item => item.group === 'inDev')
    },
    customizedLayoutItems () {
      return this.layoutLists.filter(item => item.group === 'customized')
    },
    slicerComponents () {
      return this.gadgetInfos.filter(item => slicerGadgetTypeList.some(i => item.gadgetType === i))
    },
    hasRemote(){
      return this.gadgets.some(item=>item.com === "RemoteGadget")&&this.$route.name === 'publicReport'
    }
  },
  async created () {
    if (window.location.pathname.includes('/publicReport')) {
      try {
        if(this.$route.path === '/publicReport') {
          const SECRET_KEY = CryptoJS.enc.Utf8.parse('3333e6e143439161')
          const SECRET_IV = CryptoJS.enc.Utf8.parse('e3bbe7e3ba84431a')
          // if(this.$route.fullPath.includes('shareToken=')) {
          //   let str = encodeURIComponent(this.$route.fullPath.split('/publicReport?')[1])
          //   let res = CryptoJS.AES.encrypt(str, SECRET_KEY, {
          //     iv: SECRET_IV,
          //     mode: CryptoJS.mode.CBC,
          //     padding: CryptoJS.pad.Pkcs7
          //   })
          //   let result = (res.toString())
          //   this.$router.push({
          //     path: '/publicReport',
          //     query: {
          //       tk: result
          //     }
          //   })
          // }
          if (this.$route.query.tk) {
            let tk = this.$route.query.tk
            let res = CryptoJS.AES.decrypt(tk, SECRET_KEY, {
              iv: SECRET_IV,
              mode: CryptoJS.mode.CBC,
              padding: CryptoJS.pad.Pkcs7
            })
            let result = (res.toString(CryptoJS.enc.Utf8))
            let result1 = parseQueryString(result)
            for(var key in result1) {
              this.$route.query[key] = result1[key]
            }
          }
        }
      } catch (error) {
        this.$router.push('/page-404')
        throw new Error(error)
      }
      this.createMethod()
    } else {
      try {
        if(this.needCheck) {
          let res = this.$store.state.contentTabs.find(i=>i.menuId === this.$store.state.contentTabsActiveName)
          if(res) {
            if(res.name === 'home') {
              if(this.$store.state.user.homePage) {
                this.pageId = this.$store.state.user.homePage
              }else {
                this.pageId = 'home'
              }
            }else {
              this.pageId = res.query.pageid
            }
          }
        }
      } catch (error) {
      }
      try {
        this.authLoading = true
        if (this.pageId && this.pageId !== 'home') {
          await this.getDashboardAuth()
        } else {
          this.permission = true
        }

        this.getQureAll()
        this.getDashboardLayout()

        //this.getPaidProduct()
      } catch (error) {

      } finally {
        this.authLoading = false
      }
    }
    try {
      let _self = this
      window.addEventListener('resize', debounce(()=>{
        if (_self.fitToHeight) {
          if (_self.$route.path.includes('/dashboard-') || _self.$route.path.includes('/present')) {
            _self.zoomNumber = 1
            _self.updataLayout()
          }
        }
      },300))
    } catch (error) {

    }
  },
  activated () {
    this.gadgetMessageBus.$on(this.pageId + 'mouseevent', (e) => {
      this.moveComponent(e)
    })
    this.gadgetMessageBus.$on(this.pageId + 'addgauge', (e) => {
      this.addgauge()
    })
    this.gadgetMessageBus.$on(this.pageId + 'toggleClick', (e,type) => {
      this.toggleClick(type)
    })
    this.gadgetMessageBus.$on(this.pageId + 'showEditMode', (e) => {
      this.showEditMode()
    })
    this.gadgetMessageBus.$on(this.pageId + 'hideEditMode', (e) => {
      this.hideEditMode()
    })
    this.gadgetMessageBus.$on(this.pageId + 'emitselectedgadgetPop', (e) => {
      this.selectedgadgetPop(e)
    })
  },
  deactivated () {
    this.gadgetMessageBus.$off(this.pageId + 'mouseevent')
    this.gadgetMessageBus.$off(this.pageId + 'addgauge')
    this.gadgetMessageBus.$off(this.pageId + 'toggleClick')
    this.gadgetMessageBus.$off(this.pageId + 'showEditMode')
    this.gadgetMessageBus.$off(this.pageId + 'hideEditMode')
    this.gadgetMessageBus.$off(this.pageId + 'emitselectedgadgetPop')
  },
  beforeDestroy () {
    this.gadgetMessageBus.$off()
  },

  methods: {
    async getPaidProduct () {
      try {
        const {
          getPaidProduct
        } = this.$interface.pay
        const {
          data: response
        } = await getPaidProduct()
        if (response.code !== 0) {
          throw response.msg
        }
        InterceptContext.paidProducts = response.data
      } catch (error) {

      }
    },
    createMethod (pw) {
      let _self = this
      if (this.$route.path === '/publicReportPdf') {
          this.pageId = this.$route.query.pageid
          sessionStorage.setItem('resourceId', this.pageid)
          _self.$store.state.user.tenantCode = this.$route.query.tenantCode
          window.location.protocol === 'https:'? Cookies.set('tenant_code', this.$route.query.tenantCode, {
            sameSite: 'None',
            secure: true
          }) : Cookies.set('tenant_code', this.$route.query.tenantCode)
          _self.getQureAll()
          _self.getDashboardLayout()
          _self.gadgetMessageBus.$on(_self.pageId + 'mouseevent', (e) => {
            _self.moveComponent(e)
          })
          _self.gadgetMessageBus.$on(_self.pageId + 'addgauge', (e) => {
            _self.addgauge()
          })
          _self.gadgetMessageBus.$on(_self.pageId + 'toggleClick', (e,type) => {
            _self.toggleClick(type)
          })
          _self.gadgetMessageBus.$on(_self.pageId + 'showEditMode', (e) => {
            _self.showEditMode()
          })
          _self.gadgetMessageBus.$on(_self.pageId + 'hideEditMode', (e) => {
            _self.hideEditMode()
          })
       
      } else {
        _self.validatePublishReport(pw).then(({
          data: res
        }) => {
          if(res.code === 10051&&this.$route.path==='/publicReport') {
            return this.$router.push('/page-404')
          }else if (res.code === 10050) {
            this.$store.commit('SET_API_LOAD_STATUS', false)
            this.$message(res.msg)
            this.showFixed(res.code)
            return false
          } else if (res.code === 10009) {
            this.$store.commit('SET_API_LOAD_STATUS', false)
            this.$message(res.msg)
            this.showFixed(res.code)
            return false
          } else if (res.code === 0) {
            if (!this.pageId) {
              this.pageId = res.data.resourceId
              this.eventBus&&this.eventBus()
              sessionStorage.setItem('resourceId', res.data.resourceId)
            }
            this.password = false
            this.ip = false
            window.location.protocol === 'https:'? Cookies.set('tenant_code', res.data.tenantCode, {
              sameSite: 'None',
              secure: true
            }) : Cookies.set('tenant_code', res.data.tenantCode)
            _self.$store.state.user.tenantCode = res.data.tenantCode
            _self.$store.state.user.timezoneId = res.data.timezoneId
            _self.$store.state.user.timezoneOffset = res.data.timezoneOffset
            // _self.$store.state.user.autotaskUrl = res.data.domainUrl.autotaskUrl
            // _self.$store.state.user.syncroMspUrl = res.data.domainUrl.syncroMspUrl
            // _self.$store.state.user.haloUrl = res.data.domainUrl.haloUrl
            // _self.$store.state.user.cwUrl = res.data.domainUrl.cwUrl
            _self.$store.state.user.domainUrl = res.data.domainUrl
            _self.$store.state.user.timeFormat = res.data.timeFormat
            _self.$store.state.user.shareToken = this.$route.query.shareToken
            _self.getQureAll()
            _self.getDashboardLayout()
            _self.gadgetMessageBus.$on(_self.pageId + 'mouseevent', (e) => {
              _self.moveComponent(e)
            })
            _self.gadgetMessageBus.$on(_self.pageId + 'addgauge', (e) => {
              _self.addgauge()
            })
            _self.gadgetMessageBus.$on(_self.pageId + 'toggleClick', (e,type) => {
              _self.toggleClick(type)
            })
            _self.gadgetMessageBus.$on(_self.pageId + 'showEditMode', (e) => {
              _self.showEditMode()
            })
            _self.gadgetMessageBus.$on(_self.pageId + 'hideEditMode', (e) => {
              _self.hideEditMode()
            })
            // _self.gadgetMessageBus.$on(_self.pageId + 'delDadget', (e) => { _self.closeComponent(e) })
          } else {
            _self.$router.replace({
              name: 'login'
            })
          }
        })
      }
    },
    validatePublishReport (pw) {
      let params = {
        userId: null,
        password: pw
      }
      if (this.$route.query.pageid) {
        params.resourceId = this.$route.query.pageid
      } else {
        params.shareToken = this.$route.query.shareToken
      }
      return this.$interface.reports.getFormDataApiValid(params)
    },
    addgauge () {
      this.editMode = true
      this.dashbordDefaultSetting.allowResizing = true
      this.editText = 'Save'
      this.selectedgadgetPop()
      this.gadgetMessageBus.$emit(this.pageId + 'showDesign')
    },
    showEditMode () {
      this.editMode = true
      this.dashbordDefaultSetting.allowResizing = true
    },
    hideEditMode () {
      this.editMode = false
      this.dashbordDefaultSetting.allowResizing = false
    },
    async getWidgets (gadgetId) {

      const {
        modelInfo
      } = this.$interface.reports
      const params = {
        gadgetId
      }

      let {
        data: response
      } = await modelInfo(params)

      return response.data || []
    },
    async getDashboardAuth () {
      const { getAssert } = this.$interface.system
      const { pageid } = this.$route.query
      const params = {
        sourceId: pageid || this.pageId,
        sourceType: 0
      }
      const { data: response } = await getAssert(params)
      if (response.code === 403) {
        throw 'no permission'
      }
      this.clonable = response.data.clonable

      this.permission = true
    },
    updataLayout () {
      var _self = this
      var chartDom = document.querySelector(`.vue_grid_layout_${_self.pageId}`)
      if (!chartDom) {
        setTimeout(() => {
          _self.updataLayout()
        }, 1000)
      } else {
        let domHeight = chartDom.clientHeight
        let domWidth = chartDom.clientWidth
        let bodyHeight = document.body.clientHeight
        this.zoomNumber = (bodyHeight - 175) / domHeight
        this.gadgets.forEach(item=>{
          item.h = item.com==='pageheadergadget'?item.h:item.h*this.zoomNumber
          this.resizedEvent(item.i,item.h,item.w,item.h*22-12,item.w*domWidth/12)
        })
      }
    },
    async getDashboardLayout () {
      var _self = this
      this.loading = true
      this.gadgetInfos = []
      this.gadgetLoadingStatus = []
      if (!this.pageId) {
        return
      }
      const params = {
        businessId: this.pageId
      }
      try {
        if (_self.$store.state.contentTabsActiveName === 'home' && (_self.$route.path.includes('dashboard-') || _self.$route.path.includes('scorecard-'))) {
          params.businessId = 'home'
        }
      } catch (error) {

      }
      if (params.businessId === 'home') {
        if (this.$store.state.user.homePage) {
          params.businessId = this.$store.state.user.homePage
        }
      }
      var sourceTenantCode = sessionStorage.getItem('isMySelfCode') ? sessionStorage.getItem('isMySelfCode') : this.$store.state.user.tenantCode
      this.$interface.reports.getDashboardLayout(params, sourceTenantCode)
        .then(async ({
          data: res
        }) => {
          if(res.code === 10051&&this.$route.path==='/publicReport') {
            return this.$router.push('/page-404')
          }
          if(res.code === 10051&&(this.$route.path==='/present'&&this.$route.query.type === 'single')) {
            return this.$router.push('/404')
          }
          if (res.code !== 0) {
            throw this._.get(res, 'msg', '')
          }
          if (res.data) {
            _self.dashboardsDetailsData = res.data
            _self.curTheme=res.data.theme||'white'
            _self.themeSetting=res.data.themeConfig || {}
            _self.fitToHeight = res.data.fitToHeight
            _self.zoomNumber = 1
            if (_self.fitToHeight) {
              if (_self.$route.path.includes('/dashboard-') || _self.$route.path.includes('/present')) {
                _self.updataLayout()
              }
            }
            _self.layoutType = res.data.layoutType
            _self.layoutSetting = res.data.layoutSetting
            _self.layoutId = res.data.id
            _self.reportNameForPage = res.data.name

            _self.businessTypeForWidget = res.data.businessType
            _self.reportIntegrationCode = res.data.integrationCode ? res.data.integrationCode : []
            _self.dashboardSetting = res.data.dashboardSetting ? res.data.dashboardSetting : {}
            if(_self.$route.path.includes('/report-')){
              _self.dashboardSetting = {
                size: "A4", 
                orientation: "portrait",
                ..._self.dashboardSetting
              }
            }
            _self.dashboardId = res.data.id

            // has error, need fix
            const prepareWidget = this.$store.state.ai.prepareWidget
            if(prepareWidget){
              const { gadgetId, gadgetType, id, name } = prepareWidget
   
              res.data.contentNew.push({
                "x": 0,
                "y": 0,
                "w": 6,
                "h": 21,
                "i": gadgetId,
                "com": gadgetType,
                "id": id,
                "name": name,
                "businessType": "Custom",
                "moved": false
              })
            }

            const gadgets = ((res.data.contentNew && res.data.contentNew.length) > 0 ? res.data.contentNew.filter((v,i)=>this.$route.query.currentPage!==undefined&&i!==0?i===Number(this.$route.query.currentPage)+1:true) : JSON.parse(res.data.content)) || []
            const clonewidget = JSON.parse(localStorage.getItem(`cloneWightToDashboards-${this.pageId}`))
            if(clonewidget && clonewidget.id) { 
              if (this.$route.path.includes('report-')) {
                clonewidget.h = 6
                gadgets.push({data:[clonewidget]})
              } else { 
                gadgets.splice(1, 0, clonewidget);
              }  
             }             
             if (this.isInDesktop) {
               _self.gadgets = this._.reject(gadgets, {
                 'com': 'pageheadergadget'
               })
               gadgets = this._.reject(gadgets, {
                 com: 'pageheadergadget'
               })
             }
            _self.gadgets = gadgets.map(item => {
              return {
                ...item,
                widgetName: item.name,
                integrationCode: item.integrationCode,
                gadgetType: item.com
              }
            }).sort((a,b)=>{
              return a["y"] - b["y"]
            })
            

            if(this.$route.query.currentPage!==undefined){
              this.gadgetsGrid.push(gadgets.find(v=>v.com==="pageheadergadget"))
              gadgets.forEach(v=>{
                if(v.data){
                  this.gadgetsGrid.push({data:v.data.filter(v=>v.com==='gridgadget'||slicerGadgetTypeList.includes(v.com))})
                }
              })
              res.data.contentNew.forEach((v,i)=>{
                if(i!==0&&i!==Number(this.$route.query.currentPage)+1){
                  this.otherPageSlicers=[...this.otherPageSlicers,...v.data.filter(v=>slicerGadgetTypeList.includes(v.com))]
                }
              })
              this.gadgetsGrid[this.gadgetsGrid.length-1]={
                data:[...this.gadgetsGrid[this.gadgetsGrid.length-1].data,...this.otherPageSlicers]
              }
            }
            if (this.$route.path==='/publicReportPdf'&&!this.gadgetsGrid.find(v=>v.data&&v.data.filter(v=>v.com==='gridgadget').length) && !this.$route.query.noJump) {
              this.$router.push({ name: 'publicReportPdf', query: { ...this.$route.query, pageid: this.pageId, noJump: true } });
            }
            this._.forEach(_self.gadgets, function (value, key) {
              if (value.data && value.data instanceof Array) {
                value.data.map(item => {
                  if (item.name) {
                    _self.gadgetInfos.push({
                      id: item.i,
                      gadgetStatus: 'init',
                      gadgetType: item.com ? item.com : ''
                    })
                    _self.gadgetLoadingStatus.push({
                      loadingStatus: false,
                      id: item.i,
                      gadgetType: item.com ? item.com : ''
                    })
                  }
                })
              } else {
                _self.gadgetInfos.push({
                  id: value.i,
                  gadgetStatus: 'init',
                  gadgetType: value.com ? value.com : ''
                })
                _self.gadgetLoadingStatus.push({
                  loadingStatus: false,
                  id: value.i,
                  gadgetType: value.com ? value.com : ''
                })
              }
            })
            this.otherPageSlicers.forEach(v=>{
              this.gadgetInfos.push({
                id: v.i,
                gadgetStatus: 'init',
                gadgetType: v.com ? v.com : ''
              })
              this.gadgetLoadingStatus.push({
                loadingStatus: false,
                id: v.i,
                gadgetType: v.com ? v.com : ''
              })
            })
            var slicerList = []
            var widgetList = []
            for (let index = 0; index < _self.gadgetInfos.length; index++) {
              const gadgetItem = _self.gadgetInfos[index]
              for (let i = 0; i < slicerGadgetTypeList.length; i++) {
                const element = slicerGadgetTypeList[i]
                if (element === gadgetItem.gadgetType) {
                  slicerList.push(gadgetItem)
                } else {
                  widgetList.push({
                    ...gadgetItem,
                    gadgetStatus: 'ready'
                  })
                }
              }
            }

            let newobj = {}; 
            let newArr = union(slicerList, widgetList).reduce((total, currentValue) => {
              newobj[currentValue.id] ? '' : newobj[currentValue.id] = total.push(currentValue); 
              return total
            }, [])
            _self.gadgetInfos = newArr
            for (let index = 0; index < _self.gadgets.length; index++) {
              const element = _self.gadgets[index]
              if (element.static) {
                delete element.static
              }
              if (element.com === 'pageheadergadget') {
                element.h = 3
                element.static = true
              }
            }
            _self.$store.commit('SET_GADGET_LAYOUT', _self.gadgets)
            if (!window.location.pathname.includes('/publicReport') && !window.location.pathname.includes('/publicReportPdf')) {
              if (this.getIntegrationList) this.getIntegrationList(res.data.businessId)
            }
          }
          if (params.businessId !== 'home') {

            if (!res.data.permission && res.data.permission !== undefined) {
              this.$router.replace({
                name: '404'
              })
            }
          }
          this.$store.commit('SET_API_LOAD_STATUS', false)
          if(this.eventsAutoFull){
            this.eventsAutoFull(this.gadgets)
          }
          if(window.location.pathname.includes('/report-')){
            this.settingForm = {
              size: this.dashboardSetting.size ? this.dashboardSetting.size : 'A4',
              orientation: this.dashboardSetting.orientation ? this.dashboardSetting.orientation : 'portrait'
            }
            this.currentPageSize = this._.find(this.sizeOptions, { label: this.settingForm.size })
            this.gadgets.forEach((v,i)=>{
              if(i===0){
                this.pagesData.push(v)
              }else{
                let y = (i - 1) * (this.comMaxRows + this.pageFooterH);
                Array.isArray(v.data)&&v.data.filter(v=>v.id).forEach(v=>{
                  this.pagesData.push({
                    ...v,
                    y: v.y + y
                  })
                })
                if(i!==this.gadgets.length-1){
                  const id = i + "page";
                  y = i * this.comMaxRows + this.pageFooterH * (i - 1);
                  this.pagesData.push({
                    x: 0,
                    y,
                    w: this.colNum,
                    h: this.pageFooterH,
                    i: getUUID(),
                    id,
                    static: true,
                  })
                }
              }
              this.pagesDataClone = JSON.parse(JSON.stringify(this.pagesData))
            })
          }
          this.$nextTick(() =>{
            if(!location.pathname.includes('report-')){
              if(_self.curTheme === 'white'){
                document.querySelector(".dashboard-page").removeAttribute("theme")
              }else{
                document.querySelector(".dashboard-page").setAttribute("theme", _self.curTheme)
              }

              if( _self.curTheme !== 'white' || ! _self.curTheme){
                useCssVars(_self.themeSetting)
              }
            }

            if( _self.curTheme !== 'white' || ! _self.curTheme){
              useCssVars(_self.themeSetting)
            }
          })
        }).catch((error) => {
          if (typeof error === 'string') {
            this.$message.error(error.msg)
          }
        }).finally(() => {
          this.loading = false
          this.resizedAgain()
          if(this.recordList&&!this.recordList.length){
            this.recordList.push(JSON.parse(JSON.stringify(this.pageData)))
          }
        })
    },
    resizedAgain (type) {
      this.$nextTick(() => {
        let elements
        if(type&&type === 'scorecards') {
          elements = document.querySelectorAll('.scorecard_layout_class .vue-grid-item')
        } else {
          elements = document.querySelectorAll('.report_layout .vue-grid-item') 
        }
        // console.log(Array.from(elements)[0].dataset,"Array.from(elements)");
        let dashboardArr = Array.from(elements).map((element) => {
          const {
            left,
            top
          } = element.getBoundingClientRect()
          const distance = parseInt(Math.sqrt(
            left * left + top * top
          ))
          return {
            element,
            distance
          }
        })
        dashboardArr.filter((item) => {
          return item.element.dataset.gadgettype === '0'
        }).sort((n1, n2) => (n2.distance - n1.distance))
          .forEach(({
            element
          }, index) => {
            setStyle(element, {
              'z-index': index
            })
          })
        dashboardArr.filter((item) => {
          return item.element.dataset.gadgettype === '1'
        }).sort((n1, n2) => (n1.distance - n2.distance))
          .forEach(({
            element
          }, index) => {
            setStyle(element, {
              'z-index': index
            })
          })
      })
    },
    gadgetDragChanged (e) {
      this.dashbordDefaultSetting.allowDragging = e.state
    },
    gadgetRemoved (e) {
      var index = this.getGadgetIndex(e.id)
      if(this.updateLayout){
        // let delItem=this.pageData[index]
        this.pageData.splice(index,1)
        this.$nextTick(() => {
          // this.pageData = this.updateLayout(
          //   JSON.parse(JSON.stringify(this.pageData)),delItem
          // );
          this.pageData = this.updateLayout(JSON.parse(JSON.stringify(this.pageData)));
        });
      }else{
        this.gadgets.splice(index, 1)
      }
      try {
        this.dashboardSetting.sort
        let i = this.dashboardSetting.sort.findIndex(item=>item.gadgetId === e.id)
        if(i>-1) {
          this.dashboardSetting.sort.splice(i,1)
        }
      } catch (error) {
        
      }
      // this.onSave()
      // this.gadgetMessageBus.$emit(this.pageId + 'gadgetremoved', e.id)
    },
    getGadgetIndex (id) {
      if (this.pageData) {
        for (var i = 0; i < this.pageData.length; i++) {
          if (this.pageData[i].i === id) {
            return i
          }
        }
      } else {
        for (var i = 0; i < this.gadgets.length; i++) {
          if (this.gadgets[i].i === id) {
            return i
          }
        }
      }
    },
    onSave (type) {
      for (let i = 0; i < this.gadgets.length; i++) {
        const element = this.gadgets[i]
        this.$delete(element, 'businessType')
        if (element.name) delete element.name
        if (element.com === 'pageheadergadget' || element.com === 'pageheadergadgetnexticket') {
          element.x = 0
          element.y = 0
          element.w = 12
          element.h = 3
        }
      }
      const serializeGadgets = this.gadgets.map(item => {
        const {
          config,
          widgetName,
          integrationCode,
          gadgetType,
          ...rest
        } = item

        return rest
      })
      let dashboardlayout = JSON.stringify(serializeGadgets)
      if (dashboardlayout) {
        try {
          serializeGadgets.forEach(item=>{
            if(item.com !== 'pageheadergadget') {
              let res = this.dashboardSetting.sort.some(i=>i.gadgetId === item.i)
              if(!res) {
                this.dashboardSetting.sort.push({
                  sort:Math.max.apply(Math,this.dashboardSetting.sort.map(item => { return item.sort }))+1,
                  gadgetId:item.i
                })
              }
            }
          })
          this.dashboardSetting.sort.forEach((item,index)=>{
            if(!item.headerName) {
              let res = serializeGadgets.some(i=>i.i===item.gadgetId)
              if(!res) {
                this.dashboardSetting.sort.splice(index,1)
              }
            }
          })
        } catch (error) {
          
        }
        try {
          
          if(this.$route.path.includes('report-')) {
            this.dashboardSetting = {
              ...this.dashboardSetting,
              ...this.settingForm
            }
          }
          if(this.$route.path.includes('scorecard-')) {
            this.dashboardSetting = {
              ...this.dashboardSetting,
              ...this.layoutSettingForm
            }
          }
        } catch (error) {
          
        }
        let params = {}
        if (type === 'fitToHeight') {
          params = {
            id: this.dashboardId,
            fitToHeight: this.fitToHeight,
          }
        } else {
          params = {
            tenantCode: this.$store.state.user.tenantCode,
            type: 1,
            businessId: this.pageId,
            content: dashboardlayout,
            contentNew: serializeGadgets.filter(i=>!i.headerName),
            id: this.dashboardId,
            fitToHeight: this.fitToHeight,
            dashboardSetting: Object.assign({}, this.dashboardSetting)
          }
        }
        this.$interface.reports[type === 'fitToHeight'?'updateDashboardLayout':'saveDashboardLayout'](params).then(({
          data: res
        }) => {
          this.gadgetMessageBus.$emit(this.pageId + 'closeLoading')
          if (res.code !== 0) {
            this.editMode = true
            return this.$message.error(res.msg)
          } else {
            this.showMsg = false
            this.$store.state.contentIsNeedRefresh = true
            this.$nextTick(() => {
              this.$store.state.contentIsNeedRefresh = false
            })
            return this.$message.success(this.$t('custom.dashboard.layoutSavedMessage') + res.msg)
          }
        })
      }
    },
    toggleClick (type) {
      this.editMode = !this.editMode
      if (this.editMode) {
        this.dashbordDefaultSetting.allowResizing = true
        this.editText = 'Save'
      } else {
        this.onSave(type)
        this.dashbordDefaultSetting.allowResizing = false
        this.editText = 'Edit'
      }
    },
    selectedgadgetPop (val) {
      if (val) {
        this.dialog = true
      } else {
        this.gadgetChoiceModalVisible = true
        if(this.pagesData&&this.pagesDataClone){
          this.pagesDataClone = JSON.parse(JSON.stringify(this.pagesData))
        }
      }
    },
    addWidget (item, type = 'add', gadgetId = null, businessType, id, row = {}) {
      this.dialog = false
      let getI = type === 'update' ? gadgetId : getUUID()
      let newWidget = {
        'x': item.x || 0,
        'y': item.y || 0,
        'w': item.w || 6,
        'h': item.h || 16,
        'i': getI,
        com: item.key,
        // businessType: businessType,
        id: id,
        config: Object.assign({}, row.gadgetSetting),
        widgetName: row.name,
        integrationCode: row.integrationCode,
        gadgetType: row.gadgetType
      }
      this.gadgets.push(newWidget)
    },
    verifyData (element) {
      if (!element) return false;
      if (typeof element['updateChart'] !== 'function') return false;
      if (!Array.isArray(element['queryData'])) return false;
      if (!element['queryData'].length) return false;
      if (!element['gadgetSetting']) return false;
      if (!element['gadgetSetting']['titleFontSize']) return false;
      if (isNaN(parseInt(element['gadgetSetting']['titleFontSize']))) return false;
      return true
    },
    resizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      if(this.updateLayout){
        this.pageData = this.updateLayout(
          JSON.parse(JSON.stringify(this.pageData))
        );
      }
      // this.gadgets[index].h = newH
      // this.gadgets[index].w = newW
      let refsList = this.$refs.gadgets || []
      let refList = this.$refs[`gadgets-${index}`] || []
      if (refList && refList[0]) {
        refList[0].resized(i, newH, newW, newHPx, newWPx)
        if (this.verifyData(refList[0])) {
          refList[0]['updateChart'](refList[0]['queryData'])
        }
        return
      }
      for (let ind = 0; ind < refsList.length; ind++) {
        const elementId = refsList[ind].id
        if (elementId === i && index > -1) {
          this.$refs.gadgets[ind].resized(i, newH, newW, newHPx, newWPx)
          if (this.verifyData(this.$refs.gadgets[ind])) {
            this.$refs.gadgets[ind]['updateChart'](this.$refs.gadgets[ind]['queryData'])
          }
        }
      }
      //this.$refs.gadgets[index].resized(i, newH, newW, newHPx, newWPx)
    },
    containerResizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      this.gadgets[index].h = newH
      this.gadgets[index].w = newW
      let refsList = this.$refs.gadgets || []
      for (let ind = 0; ind < refsList.length; ind++) {
        const elementId = refsList[ind].id
        if (elementId === i && index > -1) {
          this.$refs.gadgets[ind].containerResizedEvent(i, newH, newW, newHPx, newWPx)
          this.$refs.gadgets[ind].resized(i, newH, newW, newHPx, newWPx)
        }
      }
      // this.$refs.gadgets[index].containerResizedEvent(i, newH, newW, newHPx, newWPx)
    },
    mouseEnterModule (index) {
      if (this.editMode) {
        this.$set(this.gadgets[index], 'showSetting', 'show')
      }
    },
    mouseLeaveModule (index,type) {
      if (this.editMode) {
        this.$delete(this.gadgets[index], 'showSetting')
      }
      this.resizedAgain(type)
    },
    moveComponent (status) {
      if (this.editMode) {
        this.gadgetDragChanged({
          state: status
        })
      }
    },
    editComponent (componentId, item = {}) {
      try {
        if (item.businessType === 'Template' && !this.$hasPermission('sys:widget:allowedittemplatewidget')) {
          this.$store.state.userTemplateClone = true
          this.$store.state.userTemplateCloneId = item.id
          this.userTemplateClone(item)
        } else {
          let index = this.getGadgetIndex(componentId)
          // this.$refs.gadgets[index].showQueryModel()
          let refsList = this.$refs.gadgets || []
          let refList = this.$refs[`gadgets-${index}`] || []
          if (refList && refList[0]) {
            refList[0].showQueryModel()
            return
          }
          for (let i = 0; i < refsList.length; i++) {
            const elementId = refsList[i].id
            if (elementId === componentId && index > -1) {
              this.$refs.gadgets[i].showQueryModel()
            }
          }
        }
      } catch (error) {

      }
    },
    closeComponent (componentId) {
      let confirmText = [
        'Are you sure to remove widget from dashboard layout?',
        'Click confirm will continue remove widget and save layout'
      ]
      const newDatas = []
      const h = this.$createElement
      for (const i in confirmText) {
        newDatas.push(h('p', null, confirmText[i]))
      }
      this.$confirm('info', {
        title: this.$t('prompt.title'),
        message: h('div', null, newDatas),
        showCancelButton: true,
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(async () => {
        this.gadgetRemoved({
          id: componentId
        })
      }).catch(_ => { })
    },
    getQureAll () {
      try {
        var temp = {}
        if (window.location.pathname.includes('publicReport')) {
          
          const [_, path] = this.$route.fullPath.split('?')
          const query = queryToObject(path)
    
          temp = Object.assign(this.slicer, omit(query, ['pageid','appResourceList']))
  
        } else {
          let qureObj = {}
          let hasQure = decodeURIComponent(window.location.search).split('?').length > 1
          hasQure && decodeURIComponent(window.location.search).split('?')[1].split('&').map(e => {
            qureObj[e.split('=')[0]] = `${e.split('=')[1]}`
          })
          if (qureObj.pageid) {
            delete qureObj.pageid
          }
          if (qureObj.appResourceList) {
            delete qureObj.appResourceList
          }
          temp = this._.merge(this.slicer, qureObj)
        }
        this.slicer = temp
      } catch (error) { 
        console.log(error,12321)
      }
    },
    addGadgetToPage (row) {
      if (this.gadgets.findIndex(e => e.i === row.gadgetId) > -1) {
        return this.$message.error(this.$t('custom.report.disabledAddSaveGadget'))
      }
      let itemWidget = this.layoutLists.find(e => e.key === row.gadgetType)
      this.addWidget(itemWidget, 'update', row.gadgetId, row.businessType, row.id, row)
    },
    deleteGadgetToPage (row) {
      const params = {
        ...row,
        reuse: false
      }
      this.$interface.reports.postReportSetting(params).then(({
        data: res
      }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.showSettingInternal = false
        this.$emit('queryModelClosed', this.showSettingInternal)
        return this.$message.success(res.msg)
      }).catch(() => { })
    },
    fullScreen ({id,type}) {
      if(type==='in'){
        if(this.pageData){
          this.pageData.forEach(v=>{
            if(v.i===id)this.fullScreenData=v
          })
        }else{
          this.gadgets.forEach(v=>{
            if(v.i===id)this.fullScreenData=v
          })
        }
        this.isFullScreen=true
      }else{
        this.isFullScreen=false
      }
    },
  }
}
